"""
Reference: https://bailian.console.aliyun.com/?tab=doc#/doc/?type=model&url=https%3A%2F%2Fhelp.aliyun.com%2Fdocument_detail%2F2845871.html&renderType=iframe
"""
import random
from http import HTTPStatus
from dashscope import Generation  # 建议dashscope SDK 的版本 >= 1.14.0
import dashscope
import os
from openai import OpenAI
import base64
#  base 64 编码格式
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

class QwenVLModel:
    api_key = os.environ.get('DASHSCOPE_API_KEY')

    def __init__(self, model='qwen-vl-max-latest'):  # qwen-turbo, qwen-max, qwen-plus, qwen1.5-110b-chat, qwen-long, qwen1.5-72b-chat, qwen1.5-32b-chat
        self.model = model
        self.client = OpenAI(
            api_key=self.api_key,
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )


    def chat(self, image_url, prompt):
        if not image_url.startswith('http'):
            # 如果是本地图片路径，则转换为 base64 编码
            image_content = encode_image(image_url)
            if image_url.endswith('.png'):
                image_url = f"data:image/png;base64,{image_content}"
            elif image_url.endswith('.jpg') or image_url.endswith('.jpeg'):
                image_url = f"data:image/jpeg;base64,{image_content}"

        messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                    {'role': 'user', 'content': [{"type": "image_url", "image_url": {"url": image_url}}, {"type": "text", "text": prompt}]}]
        completion = self.client.chat.completions.create(model=self.model, messages=messages)
        return completion.choices[0].message.content


if __name__ == '__main__':
    # call_with_messages()
    model = QwenVLModel(model='qwen-vl-max-2025-04-08')
    prompt = """
Analyze the product in the image and output the JSON format result as follows. Result should be in English. Normal words must be lowercase. Abbreviations should be in uppercase.:
{
"shape_level_1": <Output first level shape classification, such as geometry, vegetables and fruits, animals and plants, human organs, etc>,
"shape_level_2": <English output second level shape classification, such as spherical, apple, palm, tooth, etc. If there are multiple outputs, please separate them with commas>,
"material_1": <Output the first possible material type, such as silicone, tpr>,
"material_2": <Output the second possible material type, such as silicone, tpr>,
"material_3": <Output the third possible material type, such as silicone, tpr>,
"top_colors": <Output the top three colors of the product, such as red, blue, green>,
"single_or_combination": <Output whether the product is a single item or a combination of multiple items, such as single, combination>,
}
###
Here is the reference information for the product:
Product title: Outus 24 Pcs Fruit Stress Balls Bulk Inspirational Squeeze Balls Positive Gift Foodie Fidgets Watermelon Veggie Foam Toy for Coworker Employee Fruit Graduation Party Favor (Classic)
Product bullet points: [
    "Various Options: there are 24 pieces of squeeze fruit toys in 8 kinds of different fruits, 3 pieces for each fruit, such a huge quantity provides you with various choices, and will help you drive away the boredom and enjoy the happy time, and you can share the happiness with your family and colleagues",
    "Material and Size Details: the fruit stress ball is made of quality PU material, safe, soft, reliable and comfortable, which are unbreakable and not easy to fade, and the size is about 1.6 inches to 3.2 inches, a suitable size for you to hold, portable enough and easy to carry, which can provide you with long lasting fun",
    "Interesting Universality: the new term gift fruit toy has funny pattern and attractive appearance and shape, which is popular with both young and old, suitable for most people including office employees and teachers, sports players, doctors, graduates and nurses, and it can be a good tool to help the elderly exercise the flexibility of their fingers",
    "Stress Relief: with the satisfyingly soft texture, our fruit party favors can relieve your anxiety and stress to make you feel relaxed after work or study, a fun toy to squeeze and play with every day, besides it can be applied as a desk decoration to create a cozy environment",
    "Inspirational Present: each food toy has been designed with an inspiring sentence which can encourage you when feel tired, making you feel powerful and full of energy to do better, bringing you good mood while getting good performance"
]
    """
    image_url = 'https://m.media-amazon.com/images/I/81c0kT+oqmL._AC_SX679_.jpg'
    result = model.chat(image_url, prompt)
    print(result)
